﻿using OrderSystem.Common;
using OrderSystem.DataAccess;
using OrderSystem.Templet;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace OrderSystem
{
    public partial class FormBalance : FormTemplet
    {
        private int _nCustomerID = -1;

        public FormBalance()
        {
            InitializeComponent();
        }

        private void btnSelectCustomer_Click(object sender, EventArgs e)
        {
            CustomerData customerData = FormSelectCustomer.ShowBox();
            if (customerData != null)
            {
                this._nCustomerID = customerData.CustomerID;
                this.txtCustomerName.Text = customerData.CompanyName + "(" + customerData.Linkman + ")";
            }
            this.txtYingfukuan.Text = "";
            this.txtYifukuan.Text = "";
            this.txtBalance.Text = "";
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (this.txtCustomerName.Text.Trim() != "")
            {
                if (this.txtCustomerName.Text.Trim() == "" || this._nCustomerID == -1)
                {
                    MessageBox.Show("请选择客户!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    this.txtCustomerName.Focus();
                    return;
                }
            }
            Payments payments = new Payments();
            DataSet dataSet = null;
            try
            {
                dataSet = payments.GetBalance(this._nCustomerID);
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message + "\r\n\r\n数据库出现了错误", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception ex2)
            {
                MessageBox.Show(ex2.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            payments.Dispose();
            if (dataSet != null)
            {
                if (dataSet.Tables.Count == 2)
                {
                    this.txtYingfukuan.Text = dataSet.Tables[0].Rows[0][0].ToString();
                    this.txtYifukuan.Text = dataSet.Tables[1].Rows[0][0].ToString();
                }
            }
            if (this.txtYingfukuan.Text != "" && this.txtYingfukuan.Text != null)
            {
                decimal d = Convert.ToDecimal(this.txtYingfukuan.Text);
                decimal d2 = Convert.ToDecimal(this.txtYifukuan.Text);
                if (d > d2)
                {
                    this.txtBalance.Text = "未付款：" + (d - d2).ToString();
                }
                else
                {
                    this.txtBalance.Text = (d - d2).ToString();
                }
            }
            if (dataSet != null)
            {
                dataSet.Dispose();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            base.Close();
        }
    }
}
